package com.client;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author @追风少年
 * @description NIO CLIENT
 * @date 2022/4/12
 */
public class NIOClient {

    public static void main(String[] args) throws Exception {
        // 获取网络通道
        SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞
        socketChannel.configureBlocking(false);

        // 获取IP和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8888);

        // 连接
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("连接需要时间，客户端不会堵塞，可以进行其他工作");
            }
        }

        // 开始发送数据
        Scanner scan = new Scanner(System.in);
        while(scan.hasNextLine()) {
            String content = scan.nextLine();
            // 创建buffer
            ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8));
            // 将buffer写进channel
            socketChannel.write(byteBuffer);
        }

    }

}
